﻿using LtccApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LtccApi.Controllers
{
    /// <summary>
    /// 汽车轮胎列表的全部品牌下拉项数据
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CarTireBrandFirstLetterController : Controller
    {
        private LtccContext mLtccContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ltccContext"></param>
        public CarTireBrandFirstLetterController(LtccContext ltccContext)
        {
            mLtccContext = ltccContext;
        }

        /// <summary>
        /// 轮胎品牌列表
        /// </summary>
        /// <returns>The list.</returns>
        [HttpGet]
        public IActionResult List()
        {
            //查询所有的首字母
            List<string> firstLetter = new List<string>();
            firstLetter = mLtccContext.CarBrands.OrderBy(m => m.FirstName).Select(m => m.FirstName).Distinct().ToList();
            //返回的数据
            List<CarTireBrandFirstLetter> listData = new List<CarTireBrandFirstLetter>();
            //查询所有数据  //这里最好放到客户端处理
            var allQueryResult = mLtccContext.CarBrands.OrderBy(m => m.FirstName);
            CarTireBrandFirstLetter allFirstLetter = new CarTireBrandFirstLetter();
            allFirstLetter.FirstLetter = "全部";
            allFirstLetter.TireName = allQueryResult.ToList();
            listData.Add(allFirstLetter);
            //查询数据
            var qurerResult = mLtccContext.CarBrands.AsQueryable();
            //依次将每个首字母的列表数据添加
            foreach (string letter in firstLetter)
            {
                CarTireBrandFirstLetter tmpFirstLetter = new CarTireBrandFirstLetter();
                tmpFirstLetter.FirstLetter = letter;
                List<CarBrand> tmpCarBrandList = qurerResult.Where(m => m.FirstName == letter).ToList();
                tmpFirstLetter.TireName = tmpCarBrandList;

                listData.Add(tmpFirstLetter);
            }

            return Ok(listData);
        }
    }
}
